package flc.ast.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.view.View;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.ToastUtils;

import java.io.File;

import flc.ast.BaseAc;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.databinding.ActivityPdfResultBinding;
import flc.ast.dialog.FileNameDialog;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.RxUtil;

public class PdfResultActivity extends BaseAc<ActivityPdfResultBinding> {

    public static String savePath;

    @Override
    protected int onCreate() {
        return R.layout.activity_pdf_result;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);

        mDataBinding.ivPdfResultBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.tvSave.setOnClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.tvSave://保存
                showFileNameDialog();
                break;
        }
    }

    @Override
    protected void initData() {
        mDataBinding.pdfView.fromFile(new File(savePath)).load();
    }

    private void showFileNameDialog() {
        FileNameDialog dialog = new FileNameDialog(mContext);

        dialog.name = FileUtils.getFileNameNoExtension(savePath);

        dialog.setListener(new FileNameDialog.Ilistener() {
            @Override
            public void clickRename(String name) {
                renameFile(name);
            }
        });

        dialog.show();
    }

    //重命名文件
    private void renameFile(String newName) {
        showDialog(getString(R.string.save_ing));
        RxUtil.create(new RxUtil.Callback<String>() {
            @Override
            public void doBackground(ObservableEmitter<String> emitter) {
                String suffix = FileUtils.getFileExtension(savePath);
                String desPath = PathUtils.getExternalDocumentsPath() + "/" + getPackageName() + "/" + newName + "." + suffix;
                FileUtils.copy(savePath, desPath);
                emitter.onNext("");
            }

            @Override
            public void accept(String path) {
                dismissDialog();
                ToastUtils.showShort(getString(R.string.save_success));
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        startActivity(HomeActivity.class);
                    }
                }, 500);
            }
        });
    }

}